<?php
 
namespace Admin\Controller;

// +----------------------------------------------------------------------
// | 文件 MallGoodsController.class.php
// +----------------------------------------------------------------------
// | 说明 商城商品管理
// +----------------------------------------------------------------------
// | 
// +----------------------------------------------------------------------
// | Author: 谢赤心 Legend. <xcx_legender@qq.com>
// +----------------------------------------------------------------------

class MallGoodsController extends BaseManageController {


    protected $modelName = 'Common/MallGoods';
    protected $modelType = 1; 
    /**
    *删除类型的设置 true|直接删除， false|设置数据状态
    */  
    protected $is_del   = false;

    protected function _initialize()
    {
        parent::_initialize();
        $games = A('Api/Game', 'Event')->lists();
        foreach ($games as $key => $value) {
            $this->text_map['game_id'][$value['id']] = $value['name'];
        }
        
        $this->assign('options', $this->text_map);
    }

    public function _before_index()
    {
        $pos = service('Pos')->where(['type' => 'goods', 'status' => 1])->select();
        $this->assign('pos', $pos);
    }

    public function format_lists(&$lists) {
        $ids = array_column($lists, 'id');
        $stocks = D('Common/MallGoodsCdkeys')->where(['goods_id' => ['in', $ids], 'status' => 0])->group('goods_id')->getField('goods_id, COUNT(*) as stock', true);
        foreach ($lists as &$value) {
            $value['stock'] = !empty($stocks[$value['id']]) ? $stocks[$value['id']] : 0;
        }
    }


    public function _before_add(){
        if (IS_POST)
        {
            $this->check();
        }
    }

    public function _before_edit(){
        if (IS_POST)
        {
            $this->check();
        }

    }

    protected function check(){
        if (!I('name')){
            $this->error('请填写标题');
        }
        if (!I('game_id')){
            $this->error('请选择游戏');
        }
        if (!I('price')){
            $this->error('请填写金额');
        }

        $game_id = I('game_id');
        $game_name = $this->text_map['game_id'][$game_id];
        $search_keys = array_map('trim', explode(',', I('search_key', $game_name)));
        !in_array($game_name, $search_keys) && $search_keys[] = $game_name;
        $_POST['search_key'] = implode(',', array_filter($search_keys)); 
    }

    public function remind()
    {
        $params = [
            ['uid' => 0, 'actions' => ['mall']]
        ];
        event('LocalClient')->doRequest('reddot', ['data' => json_encode($params)]);
        $this->success('操作成功');
    }
}